package com.itheima.service.impl;


import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisConstant;
import com.itheima.common.exception.FileDownloadFailException;
import com.itheima.common.exception.FileUploadFailedException;
import com.itheima.common.exception.RedisNotAvailableException;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.OrderSettingVO;
import com.itheima.service.OrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class OrderSettingServiceimpl implements OrderSettingService {
    @Autowired
    AliOssUtil aliOssUtil;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    OrderSettingMapper orderSettingMapper;
    @Override
    public void updateNumberByOrderDate(OrderSetting orderSetting) {
        Integer count = orderSettingMapper.countByDate(orderSetting.getOrderDate());
        // 如果存在,则更新信息
        if (count > 0) {
            orderSettingMapper.update(orderSetting);
        } else {
            // 如果不存在.则新增信息
          orderSettingMapper.insert(orderSetting);
        }

    }

    // 2025-1  2024   2023.。。。
    @Override
    public List<OrderSettingVO> getOrderSettingByMonth(String month) {
        String str2=new String(month.substring(0,month.lastIndexOf("-")));
        String str1=new String(month.substring(month.lastIndexOf("-")+1,month.length()));

        // 先获取所有的预约数据
        List<OrderSetting> getall=orderSettingMapper.getAll();


        List<OrderSettingVO>result=new ArrayList<>();
        for(OrderSetting os:getall){
            if((os.getOrderDate().getMonth() +1)== Integer.parseInt(str1)&&(os.getOrderDate().getYear()+1900 )==Integer.parseInt(str2)){

                result.add(new OrderSettingVO(os.getOrderDate().getDate(), os.getNumber(),os.getReservations()));
            }
        }

        return result;
    }

    @Override
    public void upload(MultipartFile multipartFile) {
        SetOperations setOperations = redisTemplate.opsForSet();
if(!isRedisAvailable()){
    throw new RedisNotAvailableException(MessageConstant.PIC_UPLOAD_FAIL);
}
try {
    int index=multipartFile.getOriginalFilename().lastIndexOf(".");
    String suffix=multipartFile.getOriginalFilename().substring(index);
    String fileName= UUID.randomUUID().toString()+suffix;
   aliOssUtil.upload(multipartFile.getBytes(),fileName);
    log.info("添加redis缓存到aliyun集合{}",multipartFile);
    setOperations.add(RedisConstant.SETMEAL_PIC_RESOURCES,multipartFile);


}catch (Exception e){
    throw  new FileUploadFailedException(MessageConstant.PIC_UPLOAD_FAIL);
}
    }

    @Override
    public void download(String fileName, HttpServletResponse response) {
        String path = "templates\\" + fileName;
        // 设置响应类型: excel
        response.setContentType("application/vnd.ms-excel");
        try(
                InputStream in=this.getClass().getClassLoader().getResourceAsStream(path);
                XSSFWorkbook excel=new XSSFWorkbook(in);
                ServletOutputStream sos=response.getOutputStream();


        ){
            excel.write(sos);
        }catch(Exception e){
            throw new FileDownloadFailException(MessageConstant.DOWNLOAD_FILE_FAIL);
        }
    }

    public boolean isRedisAvailable(){
        try {
            // 使用 PING 命令检查 Redis 连接
            String result =(String) redisTemplate.execute(RedisConnectionCommands::ping);
            return "PONG".equals(result);
        } catch (Exception e) {
            log.error("Redis 连接不可用");
            return false;
        }


    }
}
